﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

public static class RectTransformHelper
{
    public static Canvas GetCanvas(this RectTransform rectTransform)
    {
        Canvas canvas = null;
        Transform transform= rectTransform;
        while (true)
        {
            transform = transform.parent;
            if (transform == null)
                break;
            var com = transform.GetComponent<CanvasScaler>();
            if (com != null)
            {
                canvas = transform.GetComponent<Canvas>();
                break;
            }
        }
        return canvas;
    }
    public static Vector2 WorldToScreenPoint(this RectTransform rectTransform)
    {
        return WorldToScreenPoint(rectTransform, rectTransform.position);
    }
    public static Vector2 WorldToScreenPoint(this RectTransform rectTransform,Vector3 worldPoint)
    {
        var canvas = GetCanvas(rectTransform);
        if (canvas.renderMode != RenderMode.ScreenSpaceCamera || canvas.worldCamera == null)
            return worldPoint;

        Camera camera;
        camera = Camera.main;
        return RectTransformUtility.WorldToScreenPoint(camera, worldPoint);
    }

    public static Vector3 ScreenPointToWorld(this RectTransform rectTransform)
    {
        return ScreenPointToWorld(rectTransform, rectTransform.WorldToScreenPoint());
    }

    public static Vector3 ScreenPointToWorld(this RectTransform rectTransform,Vector3 screenPoint)
    {
        var canvas = GetCanvas(rectTransform);
        if (canvas.renderMode != RenderMode.ScreenSpaceCamera || canvas.worldCamera == null)
            return screenPoint;
        
        Vector3 worldPos;
        Camera camera = canvas.worldCamera;
        RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, screenPoint, camera, out worldPos);
        return worldPos;
    }
}